package com.car.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.entity.Customer;
import com.car.entity.MaintenanceRecord;
import com.car.entity.RepairRecord;
import com.car.entity.Vehicle;
import com.car.mapper.CustomerMapper;
import com.car.vo.CustomerDetailVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 客户服务
 *
 * @author Car System
 */
@Service
@RequiredArgsConstructor
public class CustomerService {

    private final CustomerMapper customerMapper;
    private final VehicleService vehicleService;
    private final MaintenanceRecordService maintenanceRecordService;
    private final RepairRecordService repairRecordService;

    /**
     * 分页查询客户
     */
    public IPage<Customer> page(Integer current, Integer size, String keyword) {
        Page<Customer> page = new Page<>(current, size);
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Customer::getName, keyword)
                    .or().like(Customer::getPhone, keyword));
        }
        
        wrapper.orderByDesc(Customer::getCreateTime);
        return customerMapper.selectPage(page, wrapper);
    }

    /**
     * 查询所有客户
     */
    public List<Customer> list() {
        return customerMapper.selectList(new LambdaQueryWrapper<Customer>()
                .orderByDesc(Customer::getCreateTime));
    }

    /**
     * 根据ID查询客户
     */
    public Customer getById(Long id) {
        return customerMapper.selectById(id);
    }

    /**
     * 获取客户详情（包含车辆、保养、维修记录）
     */
    public CustomerDetailVO getDetail(Long id) {
        CustomerDetailVO detailVO = new CustomerDetailVO();
        
        // 获取客户基本信息
        Customer customer = customerMapper.selectById(id);
        if (customer == null) {
            throw new RuntimeException("客户不存在");
        }
        detailVO.setCustomer(customer);
        
        // 获取名下车辆列表
        List<Vehicle> vehicles = vehicleService.listByCustomerId(id);
        detailVO.setVehicles(vehicles);
        detailVO.setVehicleCount(vehicles.size());
        
        // 获取保养记录列表（最近10条）
        List<MaintenanceRecord> maintenanceRecords = maintenanceRecordService.listByCustomerId(id);
        if (maintenanceRecords.size() > 10) {
            maintenanceRecords = maintenanceRecords.subList(0, 10);
        }
        detailVO.setMaintenanceRecords(maintenanceRecords);
        
        // 获取保养记录总数
        LambdaQueryWrapper<MaintenanceRecord> maintenanceWrapper = new LambdaQueryWrapper<>();
        maintenanceWrapper.eq(MaintenanceRecord::getCustomerId, id);
        detailVO.setMaintenanceCount(maintenanceRecordService.listByCustomerId(id).size());
        
        // 获取维修记录列表（最近10条）
        List<RepairRecord> repairRecords = repairRecordService.listByCustomerId(id);
        if (repairRecords.size() > 10) {
            repairRecords = repairRecords.subList(0, 10);
        }
        detailVO.setRepairRecords(repairRecords);
        
        // 获取维修记录总数
        detailVO.setRepairCount(repairRecordService.listByCustomerId(id).size());
        
        return detailVO;
    }

    /**
     * 新增客户
     */
    public void save(Customer customer) {
        // 检查手机号是否已存在
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customer::getPhone, customer.getPhone());
        if (customerMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("该手机号已存在");
        }
        
        customerMapper.insert(customer);
    }

    /**
     * 更新客户
     */
    public void update(Customer customer) {
        // 检查手机号是否被其他客户使用
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customer::getPhone, customer.getPhone())
                .ne(Customer::getId, customer.getId());
        if (customerMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("该手机号已被其他客户使用");
        }
        
        customerMapper.updateById(customer);
    }

    /**
     * 删除客户
     */
    public void delete(Long id) {
        customerMapper.deleteById(id);
    }
}

